# -*- coding: utf-8 -*-
import time,json
import httplib
import urllib
from notice_app import app
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')
import requests

print '======================================='


host = "106.ihuyi.com"
sms_send_uri = "/webservice/sms.php?method=Submit"
 
#查看用户名 登录用户中心->验证码通知短信>产品总览->API接口信息->APIID
account  = "cf_jstianyi"
#查看密码 登录用户中心->验证码通知短信>产品总览->API接口信息->APIKEY
password = "83590088-812"
# 极光推送 app_key 和 master_secret
jg_app_key = u'813c9e96bc111de06dc8200f'
jg_master_secret = u'7e7cb3ac84f20c69c9c32970'

@app.task
def send_message(mobile, text):
    print mobile, text
    params = urllib.urlencode({'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' })
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    conn = httplib.HTTPConnection(host, port=80, timeout=30)
    conn.request("POST", sms_send_uri, params, headers)
    response = conn.getresponse()
    response_str = response.read()
    conn.close()
    print response_str
    return response_str


@app.task
def send_notice(value):
    print u'开始发通知啦~~~~'
    tags = []
    if value.has_key('main'):
        tags = ['zmd_app_main_'+str(item) for item in value['main']]
    message = {
        'platform':['android','ios'],
        'audience':{
            # 'alias':['admin']
            'tag':tags
        },
        'notification':{
            'android':{
                'alert':u'公告通知',
                'title':value['title'],
                'extras':{
                    # 'url':'/newsDetail',
                    'id':value['id']
                }
            },
            'ios':{
                "alert" : value['title'],
                "sound" : "sound.caf", 
                "badge" : 1, 
                "extras" : {
                    'url':'/newsDetail',
                    'id':value['id']
                }
            }
        }
    }
    message = json.dumps(message)
    https = requests.Session()
    https.auth = (jg_app_key, jg_master_secret)
    headers = {}
    headers['user-agent'] = 'jpush-api-python-client'
    headers['connection'] = 'keep-alive'
    headers['content-type'] = 'application/json;charset:utf-8'
    response = https.request('POST', "https://api.jpush.cn/v3/push", data=message, params=None, headers=headers)
    return 'notice_success'
    